package com.tongxin.van.frameworkcanary.utils;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ToastUtils;

import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.FileCallback;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.yanzhenjie.permission.AndPermission;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;


/**
 *
 * author: VanyLiu
 * email: 13212674795@163.com
 * description: 检查更新下载类
 *  使用步骤
 *  1.AppUpdateUtils.java
 *   2.res/xml/file_paths.xml
 *   3.AndroidManifest.xml中provider声明
 *
**/
public class AppUpdateUtils {
    private static final String TAG = "AppUpdateUtils";

    public static void checkUpdateVersion(final Context context, String apiUrl, OnUpdateAppCallback callback) {
        //设置3秒超时，避免卡在启动页太长时间
        OkHttpClient.Builder builder = new OkHttpClient.Builder();
        builder.readTimeout(5, TimeUnit.SECONDS);
        builder.writeTimeout(5, TimeUnit.SECONDS);
        builder.connectTimeout(5, TimeUnit.SECONDS);
        //开始请求
        OkGo.<String>get(apiUrl)
                .client(builder.build())
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        JSONObject jsonObject;
                        try {
                            jsonObject = (JSONObject) new JSONObject(response.body()).get("data");
                            int newVersionCode = Integer.valueOf((String) jsonObject.get("version"));
                            String versionName = (String) jsonObject.get("versionName");
                            String versionInfo = (String) jsonObject.get("remark");
                            String apkUrl = (String) jsonObject.get("url");
                            int currentVersioncode = AppUtils.getAppVersionCode();
                            if (newVersionCode > currentVersioncode) {
                                showUpdateDialog(context, versionName, versionInfo, apkUrl,callback);
                            } else {
                                Log.d(TAG, "APP已是最新版本");
                                callback.onFinishUpdateAppTask();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                            callback.onFinishUpdateAppTask();
                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        Log.d(TAG, "获取APP更新信息失败：" + response.body());
                        callback.onFinishUpdateAppTask();
                    }
                });


    }

    private static void showUpdateDialog(final Context context, String versionName, String versionInfo, final String url,OnUpdateAppCallback callback) {
        final AlertDialog dialog = new AlertDialog.Builder(context)
                .setCancelable(false)
                .setTitle("版本升级")
                .setMessage(versionName + "版本更新说明：\n" + versionInfo)
                .setPositiveButton("立即升级", null)
                .setNegativeButton("暂不升级", null)
                .setOnDismissListener(dialogInterface -> callback.onFinishUpdateAppTask()) //对话框消失回调
                .create();
        dialog.show();


        dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(v -> {
            startDownload(context, url, versionName, dialog);
        });

    }

    private static void startDownload(final Context context, final String url, final String versionName, AlertDialog dialog) {
        final Button btnPositive = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
        final Button btnNegative = dialog.getButton(AlertDialog.BUTTON_NEGATIVE);
        btnNegative.setVisibility(View.GONE);
        btnPositive.setOnClickListener(null);
        btnPositive.setText("下载中 0%");
        AndPermission.with(context)
                .permission(Manifest.permission.WRITE_EXTERNAL_STORAGE)
                .onGranted(permissions -> {
                    final String destFileDir = context.getExternalCacheDir().getPath();
                    final String destFileName = "lggj" + versionName + ".apk";
                    OkGo.<File>get(url)
                            .execute(new FileCallback(destFileDir, destFileName) {
                                @Override
                                public void downloadProgress(Progress progress) {
                                    super.downloadProgress(progress);
                                    btnPositive.setText("下载中 " + (int) (progress.fraction * 100) + "%");
                                }

                                @Override
                                public void onSuccess(Response<File> response) {
                                    btnNegative.setVisibility(View.VISIBLE);
                                    btnPositive.setText("安装");
                                    btnPositive.setOnClickListener(view -> {
                                        view.postDelayed(() -> {
                                            String command = "chmod " + "777" + " " + response.body().getPath();
                                            Runtime runtime = Runtime.getRuntime();
                                            try {
                                                runtime.exec(command);
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }
                                            AppUtils.installApp(response.body().getPath(), "com.szt.echain.fileprovider");
                                        }, 1000L);//延迟1s，提升交互感
                                    });
                                    btnPositive.callOnClick();
                                }

                                @Override
                                public void onError(Response<File> response) {
                                    super.onError(response);
                                    Log.e(TAG, "下载APP失败: " + response.message());
                                    ToastUtils.showShort("下载失败");
                                    btnPositive.setText("下载失败，点此重试");
                                    btnPositive.setOnClickListener(v -> startDownload(context, url, versionName, dialog));
                                }
                            });
                })
                .onDenied(permissions -> {
                    btnPositive.setText("获取权限失败，重试");
                    btnPositive.setOnClickListener(v -> startDownload(context, url, versionName, dialog));
                })
                .start();
    }


    public interface OnUpdateAppCallback {
        void onFinishUpdateAppTask(); //当更新APP任务结束时调用
    }
}
